package me.nereo.multi_image_selector;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.githang.statusbar.StatusBarCompat;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import me.nereo.multi_image_selector.bean.Image;
import me.nereo.multi_image_selector.utils.BitmapUtil;

/**
 * Multi image selector
 * Created by Nereo on 2015/4/7.
 * Updated by nereo on 2016/1/19.
 * Updated by nereo on 2016/5/18.
 */
public class MultiImageSelectorActivity extends AppCompatActivity
        implements MultiImageSelectorFragment.Callback{

    // Single choice
    public static final int MODE_SINGLE = 0;
    // Multi choice
    public static final int MODE_MULTI = 1;

    /** Max image size，int，{@link #DEFAULT_IMAGE_SIZE} by default */
    public static final String EXTRA_SELECT_COUNT = "max_select_count";
    /** Select mode，{@link #MODE_MULTI} by default */
    public static final String EXTRA_SELECT_MODE = "select_count_mode";
    /** Whether show camera，true by default */
    public static final String EXTRA_SHOW_CAMERA = "show_camera";
    public static final String TITLE_TYPE = "titletype";
    /** Result data set，ArrayList&lt;String&gt;*/
    public static final String EXTRA_RESULT = "select_result";
    /** Original data set */
    public static final String EXTRA_DEFAULT_SELECTED_LIST = "default_list";

    public static final String EXTRA_CLIP = "clip_photo";
    public static final String EXTRA_CLIP_WIDTH = "clip_photo_width";
    public static final String EXTRA_CLIP_HEIGHT = "clip_photo_height";


    public static final String ACTION_FINISH="ACTION_FINISH";
    public static final String EXTRA_BEFORE_COUNT = "before_count";
    public static final int REQUEST_IMAGE=0x99;
    // Default image size
    private static final int DEFAULT_IMAGE_SIZE = 9;
    private static final int CLIP_PHOTO = 0;
    private ArrayList<String> resultList = new ArrayList<>();
    private Button mSubmitButton;
    private int mDefaultCount = DEFAULT_IMAGE_SIZE;
    private RelativeLayout mRelativeLayoutBack;
    private RelativeLayout mRelativeLayoutBacks;
    private TextView mTextViewYuLan;
    private boolean isClip = false;
    private MultiImageSelectorFragment multiImageSelectorFragment;
    private FinishReceiver mFinishReceiver;
    private int mMode;
    private int beforeCount = 0;
    private RelativeLayout bg;
    private RelativeLayout bgm;
    private TextView title;
    private TextView titles;
    private ImageView arrows;
    private ImageView arrowss;
    private   int statusBarHeight;
    private int currentapiVersion=android.os.Build.VERSION.SDK_INT;

    private static int getStatusBarHeight(Context context) {
        int statusBarHeight = 0;
        Resources res = context.getResources();
        int resourceId = res.getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            statusBarHeight = res.getDimensionPixelSize(resourceId);
        }
        return statusBarHeight;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(R.style.MIS_NO_ACTIONBAR);//设置主题
        StatusBarCompat.setStatusBarColor(this, Color.WHITE, true);
        setContentView(R.layout.mis_activity_default);

        int camera_REQUEST_CODE = 10;
        requestCameraPremisson(this, camera_REQUEST_CODE);//申请权限
        final Intent intent = getIntent();
        mDefaultCount = intent.getIntExtra(EXTRA_SELECT_COUNT, DEFAULT_IMAGE_SIZE);
        final int mode = intent.getIntExtra(EXTRA_SELECT_MODE, MODE_MULTI);
        mMode = mode;

        final boolean isShow = intent.getBooleanExtra(EXTRA_SHOW_CAMERA, true);
        isClip = intent.getBooleanExtra(EXTRA_CLIP,false);
        int clipWidth = intent.getIntExtra(EXTRA_CLIP_WIDTH, 300);
        int clipHight = intent.getIntExtra(EXTRA_CLIP_HEIGHT, 300);
        beforeCount = intent.getIntExtra(EXTRA_BEFORE_COUNT,0);
        int type = intent.getIntExtra(TITLE_TYPE, 0);
        bg = (RelativeLayout) findViewById(R.id.rl_bg);
        bgm= (RelativeLayout) findViewById(R.id.rl_bgs);
        LinearLayout bgs = (LinearLayout) findViewById(R.id.ll_bg);
        title=(TextView)findViewById(R.id.tv_title);
        titles=(TextView)findViewById(R.id.tv_titles);
        arrows=(ImageView)findViewById(R.id.but_backtrack);
        arrowss=(ImageView)findViewById(R.id.but_backtracks);
        mRelativeLayoutBack= (RelativeLayout) findViewById(R.id.rl_back);
        mRelativeLayoutBacks= (RelativeLayout) findViewById(R.id.rl_backs);
        mTextViewYuLan= (TextView) findViewById(R.id.tv_yuLan);
//        if(currentapiVersion<20){
//          if(type!=1){
//              bg.setVisibility(View.GONE);
//              bgm.setVisibility(View.VISIBLE);
//          }
//            Window window = getWindow();
//            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            ViewGroup decorViewGroup = (ViewGroup) window.getDecorView();
//            View statusBarView = new View(window.getContext());
//             statusBarHeight = getStatusBarHeight(window.getContext());
//            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, statusBarHeight);
//            params.gravity = Gravity.TOP;
//            statusBarView.setLayoutParams(params);
//            statusBarView.setBackgroundColor(Color.parseColor("#fed000"));
//            decorViewGroup.addView(statusBarView);
//        }else {
//
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                getWindow().setStatusBarColor(Color.parseColor("#fed000"));//设置状态栏颜色
//            }
//        }
        bindEvent();
        final ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }



        if(type==1){
            setBlackTitle();
        }

        if(mode == MODE_MULTI && intent.hasExtra(EXTRA_DEFAULT_SELECTED_LIST)) {
            resultList = intent.getStringArrayListExtra(EXTRA_DEFAULT_SELECTED_LIST);
        }

        mSubmitButton = (Button) findViewById(R.id.commit);
        if(mode == MODE_MULTI){
            updateDoneText(resultList);
            mSubmitButton.setVisibility(View.VISIBLE);
            mSubmitButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(resultList != null && resultList.size() >0){
                        // Notify success
                        Intent data = new Intent();
                        data.putStringArrayListExtra(EXTRA_RESULT, resultList);
                        setResult(RESULT_OK, data);
                    }else{
                        setResult(RESULT_CANCELED);
                    }
                    finish();
                }
            });
        }else{
            mSubmitButton.setVisibility(View.GONE);
        }

        if(savedInstanceState == null){
            Bundle bundle = new Bundle();
            bundle.putInt(MultiImageSelectorFragment.EXTRA_SELECT_COUNT, mDefaultCount);
            bundle.putInt(MultiImageSelectorFragment.EXTRA_SELECT_MODE, mode);
            bundle.putBoolean(MultiImageSelectorFragment.EXTRA_SHOW_CAMERA, isShow);
            bundle.putStringArrayList(MultiImageSelectorFragment.EXTRA_DEFAULT_SELECTED_LIST, resultList);
            bundle.putInt(MultiImageSelectorFragment.EXTRA_BEFORE_COUNT, beforeCount);
            multiImageSelectorFragment= (MultiImageSelectorFragment) Fragment.instantiate(this, MultiImageSelectorFragment.class.getName(), bundle);
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.image_grid,multiImageSelectorFragment)
                    .commit();
        }
        mFinishReceiver=new FinishReceiver();
        registerReceiver(mFinishReceiver,new IntentFilter("ACTION_FINISH"));
    }

    public void setBlackTitle(){

        bg.setBackgroundResource(R.color.mis_actionbar_color1);
        arrows.setImageResource(R.drawable.common_icon_top_arrow_left_2);
        arrowss.setImageResource(R.drawable.common_icon_top_arrow_left_2);
        titles.setTextColor(ContextCompat.getColor(MultiImageSelectorActivity.this,R.color.mis_actionbar_color2));
        title.setTextColor(ContextCompat.getColor(MultiImageSelectorActivity.this,R.color.mis_actionbar_color2));
        if(currentapiVersion<20){
            bg.setVisibility(View.GONE);
            bgm.setVisibility(View.VISIBLE);
            bgm.setBackgroundResource(R.color.mis_actionbar_color1);
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            ViewGroup decorViewGroup = (ViewGroup) window.getDecorView();
            View statusBarView = new View(window.getContext());
            int statusBarHeight = getStatusBarHeight(window.getContext());
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, statusBarHeight);
            params.gravity = Gravity.TOP;
            statusBarView.setLayoutParams(params);
            statusBarView.setBackgroundColor(Color.parseColor("#1a1a1a"));
            decorViewGroup.addView(statusBarView);
        }else {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                getWindow().setStatusBarColor(Color.parseColor("#1a1a1a"));//设置状态栏颜色
            }
        }

    }
    private void bindEvent() {
        mRelativeLayoutBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mRelativeLayoutBacks.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mTextViewYuLan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(resultList==null||resultList.size()==0){
                    return;
                }
                Intent intent = new Intent(MultiImageSelectorActivity.this, LookAPhotoActivity.class);
                // 是否显示调用相机拍照
                intent.putExtra(LookAPhotoActivity.EXTRA_SHOW_CAMERA, true);
                // 最大图片选择数量
                intent.putExtra(LookAPhotoActivity.EXTRA_SELECT_COUNT, mDefaultCount);
                // 设置模式 (支持 单选/MultiImageSelectorActivity.MODE_SINGLE 或者 多选/MultiImageSelectorActivity.MODE_MULTI)
                intent.putExtra(LookAPhotoActivity.EXTRA_SELECT_MODE, LookAPhotoActivity.MODE_MULTI);
                // 默认选择图片,回填选项(支持String ArrayList)
                intent.putStringArrayListExtra(LookAPhotoActivity.EXTRA_DEFAULT_SELECTED_LIST, resultList);
                ArrayList<Image> images= new ArrayList<>();
                for(String s:resultList){
                    images.add(new Image(s," ",0));
                }
                intent.putParcelableArrayListExtra("paths",  images);
                intent.putExtra("index",0);
                startActivityForResult(intent, REQUEST_IMAGE);
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                setResult(RESULT_CANCELED);
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * Update done button by select image data
     * @param resultList selected image data
     */
    private void updateDoneText(ArrayList<String> resultList){
        int size = 0;
        if(resultList == null || resultList.size()<=0){
            mSubmitButton.setText(R.string.mis_action_done);
            mSubmitButton.setEnabled(false);
        }else{
            size = resultList.size();
            mSubmitButton.setEnabled(true);
        }
        mSubmitButton.setText(getString(R.string.mis_action_button_string,
                getString(R.string.mis_action_done), size+beforeCount, mDefaultCount));
    }

    @Override
    public void onSingleImageSelected(String path) {
        if (isClip){
            resultList.add(path);
            clipPhoto(getUri(path));
        }else {
            Intent data = new Intent();
            resultList.add(path);
            data.putStringArrayListExtra(EXTRA_RESULT, resultList);
            setResult(RESULT_OK, data);
            finish();
        }
    }

    public Uri getUri(String path){
        File file = new File(path);
        if (file.exists()){
            return Uri.fromFile(file);
        }
        return null;
    }

    /* 场景3：选择一张图片并裁剪获得一个大图 */
    private void clipPhoto(Uri imageUri) {

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(imageUri, "image/*");
//开启裁剪功能
        intent.putExtra("crop", "true");
//设定宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
//设定裁剪图片宽高
        intent.putExtra("outputX", 100);
        intent.putExtra("outputY", 100);
//要求返回数据
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CLIP_PHOTO);
    }

    private String getPhotoPath(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            File f = getFile();
            if (!f.exists()){
                try {
                    f.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            String imagePath = BitmapUtil.saveBitmapToFile(this,photo,"head"+System.currentTimeMillis(),100,true);
            return imagePath;
        }
        return null;
    }

    @NonNull
    private File getFile() {
//        if (android.os.Environment.getExternalStorageState().equals(
//                android.os.Environment.MEDIA_MOUNTED)) {
//            return new File(getCacheDir().getAbsolutePath(), System.currentTimeMillis() + "head.jpg");
//        }else {
        File f = getCacheDir();
        if (!f.exists()){
            f.mkdirs();
        }
        return new File(f,System.currentTimeMillis() + "head");
        // }
    }

    @Override
    public void onImageSelected(String path) {
        if(!resultList.contains(path)) {
            resultList.add(path);
        }
        updateDoneText(resultList);
    }

    @Override
    public void onImageUnselected(String path) {
        if(resultList.contains(path)){
            resultList.remove(path);
        }
        updateDoneText(resultList);
    }

    @Override
    public void onCameraShot(File imageFile) {
        if(imageFile != null) {
            // notify system the image has change
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(imageFile)));
            if (isClip && mMode==MODE_SINGLE) {
                resultList.add(imageFile.getAbsolutePath());
                clipPhoto(getUri(imageFile.getAbsolutePath()));
            }else {
                Intent data = new Intent();
                resultList.add(imageFile.getAbsolutePath());
                data.putStringArrayListExtra(EXTRA_RESULT, resultList);
                setResult(RESULT_OK, data);
                finish();
            }
        }
    }

    @Override
    public void onImageFold(ArrayList<Image> images) {
        ArrayList<Image> mCurrentFoldImages = images;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case  REQUEST_IMAGE:
                if(resultCode==RESULT_OK){
                    resultList=data.getStringArrayListExtra(LookAPhotoActivity.EXTRA_RESULT);
                    multiImageSelectorFragment.setDefaultSelect(resultList);
                    updateDoneText(resultList);
                }
                break;
            case CLIP_PHOTO:
                if (resultCode==RESULT_OK) {
                    if (data != null && data.getExtras() != null) {
                        resultList.clear();
                        resultList.add(getPhotoPath(data));
                        Intent dataR = new Intent();
                        dataR.putStringArrayListExtra(EXTRA_RESULT, resultList);
                        setResult(RESULT_OK, dataR);
                        finish();
                    } else {
                        Intent dataR = new Intent();
                        dataR.putStringArrayListExtra(EXTRA_RESULT, resultList);
                        setResult(RESULT_OK, dataR);
                        finish();
                    }
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mFinishReceiver);
    }

    public boolean requestCameraPremisson(Activity activity, int Camera_REQUEST_CODE){
        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED||ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    Camera_REQUEST_CODE);
            return false;
        }else {
            return true;
        }
    }

    class FinishReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if(ACTION_FINISH.equals(intent.getAction())){
                finish();
            }
        }
    }

}
